package com.yale.elasticsearch.service.base;

import co.elastic.clients.elasticsearch._types.Time;
import com.yale.elasticsearch.dto.IndexNameDTO;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.*;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 索引操作
 */
@Slf4j
@Service
public class IndexService {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 验证索引是否存在
     */
    public Object existsIndex(String indexName) {
        Object result = "";
        try {
            // 创建索引存在检查请求对象
            ExistsRequest existsRequest = ExistsRequest.of(e -> e.index(indexName)//"mydlq-user"
            );

            // 执行请求
            BooleanResponse response = elasticsearchClient.indices().exists(existsRequest);
            boolean isExist = response.value();

            // 输出索引存在状态
            log.info("是否存在：{}" , isExist);
            result = isExist;
        } catch (IOException e) {
            log.error("Error executing index exists request: {}" , e.getMessage());
        }
        return result;
    }


    /**
     * 创建索引
     */
    public Object createIndex(IndexNameDTO indexNameDTO) {
        Object result = "";
        try {
            if (indexNameDTO.getIndexField() == null || indexNameDTO.getIndexField().size() == 0) {
                log.info("索引字段不能为空");
                return false;
            }
            if (existsIndex(indexNameDTO.getIndexName()).equals(true)) {
                log.info("索引已存在，无需再创建：{}" , indexNameDTO.getIndexName());
                return false;
            }
            // Build the properties dynamically
            Map<String, Property> properties = new HashMap<>();
            for (IndexNameDTO.IndexField indexField : indexNameDTO.getIndexField()) {
                String fieldName = indexField.getFieldName();
                String fieldType = indexField.getFieldType();

                Property property;
                switch (fieldType.toLowerCase()) {
                    case "text":
                        property = Property.of(p -> p.text(TextProperty.of(t -> t)));
                        break;
                    case "integer":
                        property = Property.of(p -> p.integer(IntegerNumberProperty.of(i -> i)));
                        break;
                    case "date":
                        property = Property.of(p -> p.date(DateProperty.of(d -> d.format("yyyy-MM-dd"))));
                        break;
                    case "float":
                        property = Property.of(p -> p.float_(FloatNumberProperty.of(f -> f)));
                        break;
                    default:
                        throw new IllegalArgumentException("Unsupported field type: " + fieldType);
                }

                properties.put(fieldName, property);
            }
            // Define index settings

            CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                    .index(indexNameDTO.getIndexName()) //索引名称 mydlq-user
                    .settings(s -> s
                            .numberOfShards("1") // 分片数量
                            .numberOfReplicas("3")//副本数量
                            .refreshInterval( Time.of(t -> t.time("1s")))// 刷新间隔
                    )
                    .mappings(m -> m
                            .properties(properties)
                    )
                    .build();
            // Create index
            CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(createIndexRequest);
            boolean isCreated = createIndexResponse.acknowledged();
            log.info("是否创建成功：{}" , isCreated);
            result = isCreated;
        } catch (IOException e) {
            log.error("Error creating index: {}" , e.getMessage());
        }
        return result;
    }


    /**
     * 删除索引
     */
    public Object deleteIndex(String indexName) {
        Object result = "";
        try {
            if (existsIndex(indexName).equals(true)) {
                // 创建删除索引请求对象
                DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder()
                        .index(indexName)
                        .build();

                // 执行删除索引
                DeleteIndexResponse deleteIndexResponse = elasticsearchClient.indices().delete(deleteIndexRequest);

                // 判断是否删除成功
                boolean isDeleted = deleteIndexResponse.acknowledged();
                stringRedisTemplate.delete(indexName + "_id");
                log.info("是否删除成功：{}" , isDeleted);
                result = isDeleted;
            } else {
                log.info("索引不存在：{}" , indexName);
                return false;
            }
        } catch (IOException e) {
            log.error("Error deleting index: {}" , e.getMessage());
        }
        return result;
    }


}
